# 定义模型
from enum import IntEnum

from tortoise import Tortoise, run_async, fields, models
from tortoise.contrib.pydantic import pydantic_model_creator


class AbstractModel(models.Model):
    # 当表中所有字段都没有pk时, 默认自动生成一个IntField类型id作为主键
    id = fields.UUIDField(pk=True)

    class Meta:
        abstract = True  # 定义为抽象模型


class MixinTimeFields:
    created_at = fields.DatetimeField(auto_now_add=True, null=True)
    updated_at = fields.DatetimeField(auto_now=True)


class Gender(IntEnum):
    MAN = 1
    WOMAN = 0


class UserModel(AbstractModel, MixinTimeFields):
    username = fields.CharField(max_length=20, unique=True, index=True, description="用户名")
    nickname = fields.CharField(max_length=30, null=True, description="昵称")
    gender = fields.IntEnumField(enum_type=Gender, default=Gender.MAN, description="性别")
    balance = fields.DecimalField(max_digits=3, decimal_places=2, default=0, description="余额")
    is_admin = fields.BooleanField(default=False, description="是否为管理员")
    job_info = fields.JSONField(default={}, description="工作信息")  #  default=dict

    class Meta:
        table = "users"  # 定义表名
        table_description = "用户表"  # 定义表描述
        # 设置复合唯一索引
        unique_together = (("gender", "balance"),)
        # 排序规则
        ordering = ["-created_at"]
        # 索引
        indexes = (
            # 联合索引
            ("username", "balance"),
            # 单字段索引
            ("balance",),
        )


# 创建 Pydantic 模型
User_Pydantic = pydantic_model_creator(UserModel, name="UserSchema", exclude=("job_info",))
UserIn_Pydantic = pydantic_model_creator(UserModel, name="UserInSchema", exclude_readonly=True)
UserOut_Pydantic = pydantic_model_creator(UserModel, name="UserOutSchema", exclude=("job_info",))


# 注册模型
async def init_db():
    await Tortoise.init(
        db_url="sqlite://other/db.sqlite3",
        modules={"models": ["__main__"]},
        use_tz=False,
        timezone="Asia/Shanghai",
    )

    await Tortoise.generate_schemas()
    await curd_user()

async def curd_user():
    # 创建用户1  obj.save()
    user = UserModel(username="test1", nickname="test1_nickname", gender=Gender.MAN, balance=100.00)
    await user.save()
    
    # 创建用户2  model.create()
    await UserModel.create(username="test2", nickname="test2_nickname", gender=Gender.WOMAN, balance=200.00)


if __name__ == "__main__":
    run_async(init_db())
    # run_async(curd_user())
